package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.DonationDetailActivity;
import com.srwl.mytx.adapter.DonationRecordAdapter;
import com.srwl.mytx.adapter.DonationRecordAdapter_v1;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.widget.NodataFooter;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 用于个人主页 显示捐赠记录 （显示给别人看）
 */
public class DonationRecordFragment_v1 extends BaseFragment {
    private static final String TAG = "DonationRecordFragment";
    public static final int TO_DONATION_DETAIL = 1;
    private static final String ARG_USER_ID = "uId";
    private static final String ARG_DONATION_LIST = "donationList";
    private List<Donation> donationList = new ArrayList<>();
    private DonationRecordAdapter_v1 donationRecordAdapter;
    private String uId;
    private int page = 1;
    private static final int SIZE = 20;
    private boolean hasNextPage = true;
    private MaterialSmoothRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private LinearLayoutManager linearLayoutManager;
    private InteractionListener listener;
    private User loginUser;


    public DonationRecordFragment_v1() {
    }


    public static DonationRecordFragment_v1 newInstance(String uId) {
        DonationRecordFragment_v1 fragment = new DonationRecordFragment_v1();
        Bundle args = new Bundle();

        args.putString(ARG_USER_ID, uId);
        fragment.setArguments(args);
        return fragment;
    }

    public static DonationRecordFragment_v1 newInstance(ArrayList<Donation> donationList, String uId) {
        DonationRecordFragment_v1 fragment = new DonationRecordFragment_v1();
        Bundle args = new Bundle();
        args.putString(ARG_USER_ID, uId);
        args.putParcelableArrayList(ARG_DONATION_LIST, donationList);
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

            uId = getArguments().getString(ARG_USER_ID);

            if (getArguments().containsKey(ARG_DONATION_LIST)) {
                donationList = getArguments().getParcelableArrayList(ARG_DONATION_LIST);
            }
        }
        donationRecordAdapter = new DonationRecordAdapter_v1(getContext(), donationList);
        loginUser = UserProfileManager.getInstance().getLoginUserInfo();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.contibution_record_item_list, container, false);


        Context context = view.getContext();
        refreshLayout = view.findViewById(R.id.refresh_layout);
        recyclerView = view.findViewById(R.id.rv_donation);
        progressBar = view.findViewById(R.id.progress_bar);
        if (donationList.size() == 0) {
            if (isTempUser()) {
                donationRecordAdapter.showNoDataView();
            } else {
                loadData(true, false);
            }
        }
        linearLayoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(linearLayoutManager);
        donationRecordAdapter.setHasStableIds(true);
        recyclerView.setAdapter(donationRecordAdapter);

        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        //  refreshLayout.setEnableHeaderDrawerStyle(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnLoadMoreScrollCallback(new SmoothRefreshLayout.OnLoadMoreScrollCallback() {
            @Override
            public void onScroll(View content, float delta) {

                recyclerView.scrollBy(0, (int) delta);
            }
        });
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                Log.d(TAG, "onRefreshBegin: 正在刷新");

                // donationList.clear();
                page = 1;
                if (!isTempUser()) {
                    loadData(false, true);
                }
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage && !isTempUser()) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }
        });
        return view;
    }



    void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (isFirst && listener != null) {
            listener.showProgressBar(true);
        }
        Map<String, Object> info = new HashMap<>();
        info.put("page", page);
        info.put("size", SIZE);
        info.put("uId", uId);//查询别人捐赠记录需要携带uId
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .querySentDonations(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst && listener != null) {
                            listener.showProgressBar(false);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            donationRecordAdapter.showErrorView();

                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            showToast(getString(R.string.system_busy));
                            donationRecordAdapter.showErrorView();

                            return;
                        }
                        JSONObject pageInfo = (JSONObject) body.getData();
                        Log.d(TAG, "onResponse: 获取捐赠数据完成" + pageInfo.toString());
                        hasNextPage = pageInfo.getBoolean("hasNextPage");

                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }
                        List<Donation> donations = pageInfo.getJSONArray("list").toJavaList(Donation.class);
                        if (isRefresh) {
                            donationList.clear();
                        }
                        if (donations.size() > 0) {
                            //后端是根据uid 去查询捐赠记录，就没有查询m_id字段，这儿补充进去
                            for (Donation donation : donations) {
                                donation.setmId(uId);
                            }
                            donationList.addAll(donations);
                            donationRecordAdapter.showNormalView();
                            page++;
                        } else if (page == 1) {
                            donationRecordAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        if (isFirst && listener != null) {
                            listener.showProgressBar(false);
                        } else {
                            refreshLayout.refreshComplete();
                        }
//                        if (isFirst) {
//                            showErrorImage();
//                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        donationRecordAdapter.showErrorView();
                    }
                });
    }

    /**
     * 判断是否是游客
     *
     * @return
     */
    private boolean isTempUser() {
        if (TextUtils.equals(uId, loginUser.getuId()) && loginUser.getType() == Constant.USER_TYPE_TEMP) {
            return true;
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        if (requestCode == TO_DONATION_DETAIL) {

            Donation donation = data.getParcelableExtra("donation");
            if (donation == null) {
                return;
            }
            for (int i = 0; i < donationList.size(); i++) {
                Donation donation1 = donationList.get(i);
                if (TextUtils.equals(donation.getId(), donation1.getId())) {
                    donation1.setStatus(donation.getStatus());
                    donation1.setUpdated(donation.getUpdated());
                    donationRecordAdapter.notifyItemChanged(i);
                }
            }
        }


    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {

        void showProgressBar(boolean isShowProgressBar);
    }
}